package com.koron.css2.baseConfig.impl;


import com.alibaba.fastjson.JSONObject;
import com.koron.css2.baseConfig.bean.MeterModelBean;
import com.koron.css2.baseConfig.mapper.MeterModelMapper;
import com.koron.util.secret.RequestBean;
import com.mysql.cj.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class SyncMeterService {
	private static Logger log = LogManager.getLogger(SyncMeterService.class);

	@TaskAnnotation("getModel")
	public List<MeterModelBean> getModel(SessionFactory sessionFactory) {
		List<MeterModelBean> list;
		try {
			MeterModelMapper mapper = sessionFactory.getMapper(MeterModelMapper.class);
			list = mapper.getAll();
		} catch (Exception e) {
			log.error("累计流量查询失败", e);
			throw new RuntimeException(e.getMessage());
		}
		return list;
	}
	@TaskAnnotation("addModel")
	public String addModel(SessionFactory sessionFactory,RequestBean req) {
		try {
			MeterModelMapper mapper = sessionFactory.getMapper(MeterModelMapper.class);
			MeterModelBean bean=JSONObject.parseObject(JSONObject.toJSONString(req.getData()),MeterModelBean.class);
            // 校验字段重复
            if (mapper.check("model_name", bean.getModelName()) > 0) {
                return "水表型号名称：";
            }
            // 校验字段重复
            if (mapper.check("model_no", bean.getModelNo()) > 0) {
                return "水表型号编号：" + bean.getModelNo() + "的信息已存在。";
            }
            mapper.insertMeterModel(bean);
		} catch (Exception e) {
			log.error(e+"");
			return "新增失败";
		}
		return null;
	}
	@TaskAnnotation("updateModel")
	public String updateModel(SessionFactory sessionFactory,RequestBean req) {
		try {
			MeterModelMapper mapper = sessionFactory.getMapper(MeterModelMapper.class);
			MeterModelBean bean=JSONObject.parseObject(JSONObject.toJSONString(req.getData()),MeterModelBean.class);
			// 校验字段重复
            if (mapper.check2("model_name", bean.getModelName(), bean.getId()) > 0) {
                return "水表型号名称：" + bean.getModelName() + "的信息已存在。";
            }
            if (mapper.check2("model_no", bean.getModelNo(), bean.getId()) > 0) {
                return "水表型号编号：" + bean.getModelNo() + "的信息已存在。";
            }
            if (StringUtils.isNullOrEmpty(bean.getId())) {
                return "id为空";
            }
            mapper.updateMeterModel(bean);
		} catch (Exception e) {
			return "修改失败";
		}
		return null;
	}
}
